package com.tsd.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.tsd.core.datasource.DynamicDataSource;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: AOP切面设置全局事务
 * @Author Luoyc
 * @Date 2019/2/18 11:04
 * @Modefied By:
 */
@Configuration
@EnableTransactionManagement
@Aspect
public class TransactionManagerConfig {

    private static final int TX_METHOD_TIMEOUT = 10 * 60;
    /**
     * 定义切点变量：拦截com.tsd包下所有service类的所有方法,返回值类型任意的方法
     */
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.tsd..service..*.*(..))";

    private final DruidDataSource masterDataSource;
    private final DynamicDataSource dynamicDataSource;

    @Autowired
    public TransactionManagerConfig(DruidDataSource masterDataSource, DynamicDataSource dynamicDataSource) {
        this.masterDataSource = masterDataSource;
        this.dynamicDataSource = dynamicDataSource;
    }

//    @Autowired
//    public TransactionManagerConfig(DruidDataSource masterDataSource) {
//        this.masterDataSource = masterDataSource;
//    }

    //定义事务管理器
    @Bean
    public DataSourceTransactionManager transactionManager() {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dynamicDataSource);
        return manager;
    }

    //定义事务策略
    @Bean
    public TransactionInterceptor txAdvice() {
        //事务管理规则，声明具备事务管理的方法名
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        //只读事物、不做更新删除等
        //当前存在事务就用当前的事务，当前不存在事务就创建一个新的事务
        RuleBasedTransactionAttribute readOnlyRule = new RuleBasedTransactionAttribute();
        //设置当前事务是否为只读事务，true为只读
        readOnlyRule.setReadOnly(true);
        //transactiondefinition 定义事务的隔离级别
        //PROPAGATION_NOT_SUPPORTED事务传播级别5，以非事务运行，如果当前存在事务，则把当前事务挂起
        readOnlyRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

        RuleBasedTransactionAttribute requireRule = new RuleBasedTransactionAttribute();
        //抛出异常后执行切点回滚
        requireRule.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        //PROPAGATION_REQUIRED:事务隔离性为1，若当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。这是默认值
        requireRule.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        //设置事务失效时间，如果超过5秒，则回滚事务
        requireRule.setTimeout(TX_METHOD_TIMEOUT);

        Map<String, TransactionAttribute> txMap = new HashMap<String, TransactionAttribute>();
        txMap.put("query*", readOnlyRule);
        txMap.put("get*", readOnlyRule);
        txMap.put("find*", readOnlyRule);

        txMap.put("*", requireRule);

        source.setNameMap(txMap);
        return new TransactionInterceptor(transactionManager(), source);
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}
